import {
  primaryBackgroundColor2,
  secondaryColor,
  primaryBackgroundColor,
  primaryColor2,
  secondaryBackgroundColor,
  secondaryBorderColor,
  primaryColor,
  primaryColor3,
} from '../../../theme/default';
import {
  Image,
  Text,
  TextInput,
  TouchableOpacity,
  View,
  StyleSheet,
  Keyboard,
} from 'react-native';
import React, {useEffect, useMemo, useState} from 'react';
import tw from 'twrnc';
import {TokenLogo} from '../../UI/TokenLogo';
import {useTranslation} from 'react-i18next';
import {formatNumber, isValidSolanaAddress, parseUnits} from '../../../utils';
import BigNumber from 'bignumber.js';
import {NativeStackNavigationProp} from '@react-navigation/native-stack';

import ScanIcon from '../../../assets/icons/scan.svg';
import {RootStackParamList} from '../../Nav/routes';
import {RouteProp, useIsFocused} from '@react-navigation/native';
import {useScannerProvider} from '../../../hooks/useScannerProvider';

type SendStackNavigationProp = NativeStackNavigationProp<
  RootStackParamList,
  'Send'
>;
type SendRouteProp = RouteProp<RootStackParamList, 'Send'>;

const Send = ({
  route,
  navigation,
}: {
  route: SendRouteProp;
  navigation: SendStackNavigationProp;
}) => {
  const {tokenInfo} = route.params;
  const {t} = useTranslation();

  const isFocused = useIsFocused();
  const {codeResult, setCodeResult} = useScannerProvider();

  const [address, setAddress] = useState('');
  const [amount, setAmount] = useState('');
  const [isValidAmount, setIsValidAmount] = useState<boolean>();
  const [isValidAddress, setIsValidAddress] = useState<boolean>();

  const handleDone = () => {
    Keyboard.dismiss();
  };

  useEffect(() => {
    if (isFocused) {
      console.log('codeResult', codeResult);
      const _address = codeResult?.codeResult ?? '';
      if (_address != '') {
        setAddress(_address);
        setIsValidAddress(isValidSolanaAddress(_address));
      }
    }
  }, [codeResult]);

  useEffect(() => {
    navigation.setOptions({
      title: t('sendToken', {symbol: tokenInfo.symbol}),
    });
  }, [navigation, tokenInfo]);

  useEffect(() => {
    setAddress('');
    setAmount('');
    return () => {
      setCodeResult(undefined);
    };
  }, []);

  const transition = useMemo(() => {
    return {
      toAddress: address,
      amount: amount,
      token: tokenInfo,
    };
  }, [address, amount, navigation]);

  const handleAmountChange = (value: string) => {
    const maxDecimals = tokenInfo.decimals;
    const decimalRegex = new RegExp(`^[0-9]*\.?[0-9]{0,${maxDecimals}}$`);
    if (decimalRegex.test(value)) {
      setAmount(value);
      if (
        BigNumber(parseUnits(value, tokenInfo.decimals)).isGreaterThan(
          BigNumber(tokenInfo.amount!),
        )
      ) {
        setIsValidAmount(false);
      } else {
        setIsValidAmount(true);
      }
    }
  };

  return (
    <View
      style={tw.style(
        `bg-[${primaryBackgroundColor}] min-h-full p-4 relative`,
      )}>
      <View style={{marginBottom: 12}}>
        <View style={tw.style('flex flex-col gap-3')}>
          <View
            style={{
              ...tw.style('flex flex-col items-center gap-2'),
              paddingVertical: 24,
            }}>
            <TokenLogo
              tokenName={tokenInfo.name}
              logoUri={tokenInfo.logo}
              size={50}
              borderRadius={50}
              backgroundColor="blue"
              textFontSize={12}></TokenLogo>
            <Text style={tw.style(`text-[${primaryColor2}] text-[16px]`)}>
              {tokenInfo.symbol}
            </Text>
          </View>
          <View
            style={tw.style(
              `flex flex-row items-center justify-between gap-3 h-[50px] py-2 px-4 rounded-xl bg-[${primaryBackgroundColor2}] border border-[${
                isValidAddress == true || isValidAddress == undefined
                  ? secondaryBorderColor
                  : 'red'
              }]`,
            )}>
            <TextInput
              style={tw.style(
                `w-4/5 text-[${primaryColor2}] text-[16px] placeholder:text-[12px]`,
              )}
              placeholder={t('receiveAddressHint')}
              placeholderTextColor={primaryColor3}
              value={address}
              returnKeyType="done"
              onSubmitEditing={handleDone}
              onBlur={() => {
                if (address == '') {
                  setIsValidAddress(undefined);
                } else {
                  setIsValidAddress(isValidSolanaAddress(address));
                }
              }}
              onChangeText={setAddress}
            />
            <TouchableOpacity
              onPress={() => {
                navigation.navigate('Scanner');
              }}>
              <ScanIcon width={24} height={24} color={primaryColor3}></ScanIcon>
            </TouchableOpacity>
          </View>
          {isValidAddress === false && (
            <View>
              <Text style={{color: 'red', fontSize: 14}}>
                {t('invalidSolanaAddress')}
              </Text>
            </View>
          )}
        </View>
      </View>
      <View
        style={tw.style(
          `flex flex-col gap-1 mt-2 py-5 px-4 rounded-xl bg-[${primaryBackgroundColor2}] border border-[${
            isValidAmount == true || isValidAmount == undefined
              ? secondaryBorderColor
              : 'red'
          }]`,
        )}>
        <View
          style={tw.style(`flex flex-row items-center justify-between gap-2`)}>
          <TextInput
            style={tw.style(`w-4/5 text-[${primaryColor2}] text-[16px]`)}
            placeholder={t('amount')}
            keyboardType="numeric"
            returnKeyType="done"
            onSubmitEditing={handleDone}
            placeholderTextColor={secondaryColor}
            value={amount}
            onChangeText={handleAmountChange}
          />
          <View
            style={tw.style(
              `flex flex-row items-center justify-between gap-1`,
            )}>
            <Text style={tw.style(` text-[${primaryColor2}]`)}>
              {tokenInfo.symbol}
            </Text>
          </View>
        </View>
        <View style={styles.horizontalLine} />
        <View
          style={tw.style(
            `flex flex-row items-center justify-between text-[14px]`,
          )}>
          <Text style={tw.style(`text-[${primaryColor3}] text-[12px]`)}>
            {t('balance')}: {formatNumber(tokenInfo.uiAmount!, 2, 6)}{' '}
            {tokenInfo.symbol}
          </Text>
          <TouchableOpacity onPress={() => setAmount(tokenInfo.uiAmount!)}>
            <Text style={tw.style(`text-[${primaryColor}] text-[14px]`)}>
              {t('maxTitle')}
            </Text>
          </TouchableOpacity>
        </View>
      </View>
      {isValidAmount === false && (
        <View style={{marginTop: 8}}>
          <Text style={{color: 'red', fontSize: 14}}>
            {t('insufficientBalance')}
          </Text>
        </View>
      )}

      <TouchableOpacity
        style={styles.button}
        onPress={() => {
          console.log('数组数组：', isValidAddress, isValidAmount);
          // if (isValidAddress && isValidAmount) {
          if (isValidAmount) {
            navigation.navigate('SendConfirm', {...transition});
          }
        }}>
        <Text
          style={tw.style(
            `text-[${primaryColor2}] text-center leading-10 font-bold`,
          )}>
          {t('nextTitle')}
        </Text>
      </TouchableOpacity>
    </View>
  );
};

const styles = StyleSheet.create({
  button: {
    width: '100%',
    height: 42,
    borderColor: primaryColor,
    backgroundColor: secondaryBackgroundColor,
    borderWidth: 1,
    position: 'absolute',
    bottom: 100,
    left: 16,
    borderRadius: 16,
  },
  horizontalLine: {
    borderBottomColor: '#4e4d4d',
    borderBottomWidth: 1,
    width: '100%',
    marginVertical: 10,
  },
});
export default Send;
